package com.coconet.gas.service.impl;

import com.alibaba.fastjson.JSON;
import com.coconet.gas.constant.dwEnum;
import com.coconet.gas.dao.*;
import com.coconet.gas.dao.RecordnewMapper;
import com.coconet.gas.dao.RecordnewandgroupMapper;
import com.coconet.gas.exception.ServiceException;
import com.coconet.gas.quartz.ScanQuartzJob;
import com.coconet.gas.rabbitMq.entity.CheckEntity;
import com.coconet.gas.service.TaskService;
import com.coconet.gas.until.ScoreUtil;
import com.coconet.gas.vo.Assets;
import com.coconet.gas.vo.PageService;
import com.gxa.entity.ResultInfoPage;
import com.coconet.gas.vo.dw.*;
import com.coconet.gas.vo.request.PortListVo;
import com.gxa.entity.IpResultEntity;
import com.gxa.entity.TargetEntity;
import com.gxa.entity.TaskEntity;
import com.gxa.entity.TaskInfoEntity;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskService taskService;
    @Resource
    private TaskIpMapper taskIpMapper;
    @Resource
    private TargetIpMapper targetIpMapper;
    @Resource
    private IpsRuleMapper ipsRuleMapper;
    @Resource
    private OpenvasTool2 openvasTool;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private TaskReportRelateMapper trrMapper;
    @Autowired
    private ScanQuartzJob sqJob;
    @Resource
    private ScanQuartzMapper sqMapper;
    @Autowired
    private Scheduler scheduler;
    @Resource
    private TranslateMapper translateMapper;
    @Resource
    private RabbitMQServiceImpl rabbitMQServiceImpl;
    @Resource
    private RecordnewandgroupMapper rgMapper;
    @Resource
    private RecordnewMapper rnMapper;
    @Resource
    private AssetandgroupMapper assetandgroupMapper;
    @Resource
    private AssetsMapper assetsMapper;
    @Resource
    private MqTaskMapper mqTaskMapper;
    @Resource
    private GroupTaskMapper groupTaskMapper;
    //private OpenvasTool2 openvasTool = new OpenvasTool2();
    @Autowired
    private PageService pageService;

    @Override
    @Transactional
    public List<Report> getReportByTaskId(String taskId) throws Exception {
        String taskName = null;
        String reportId = null;
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        List<Report> reportList = new ArrayList<>();
        for (TaskInfoEntity task : tasksList) {
            if (task.getTaskId().equals(taskId)) {
                taskName = task.getName();
                reportId = task.getReportId();
            }
        }
        /*TaskIp taskIp = new TaskIp();
        taskIp.setTaskId(taskId);
        TaskIp taskIp1 = taskIpMapper.selectOne(taskIp);
        if (taskIp1 == null) {
            throw new ServiceException(dwEnum.FAILURE.code(), "扫描报告已过期,请重新开始扫描");
        } else if (taskIp1.getReportId() == null) {
            throw new ServiceException(dwEnum.FAILURE.code(), "扫描报告已过期,请重新开始扫描");
        }*/

        Report report = new Report();
        report.setTaskId(taskId);
        if (reportMapper.select(report) == null || reportMapper.select(report).size() == 0) {
            Map<String, Object> resultMap = openvasTool.getReport(reportId);
            List<Map<String, Object>> results = (List<Map<String, Object>>) resultMap.get("results");
            for (Map<String, Object> result : results) {
                String resultId = (String) result.get("resultId");
                //resultIdList.add(resultId);
                Map<String, Object> reportResult = openvasTool.getReportResult(resultId);
                //详细信息2 = {Report@12779} "Report [Hash = 884513070, id=111, taskId=dbb24fd2-3e3e-42ab-887f-5986df625f14, taskName=147TCP, cveName=CPE Inventory, cve=无CVE编号, qod=80, severity=0.0, threat=Log]"
                    /*Map<String, Object> reportResult = openvasTool.getReportResult(resultId);
                    String cve = (String) reportResult.get("cve");
                    String qod = (String) reportResult.get("qod");
                    IpsRule ipsRule = new IpsRule();
                    ipsRule.setCve(cve);
                    List<IpsRule> ipsRuleList = ipsRuleMapper.select(ipsRule);
                    String cveName = null;
                    if (ipsRuleList != null && ipsRuleList.size() > 0) {
                        cveName = ipsRuleMapper.select(ipsRule).get(0).getRname();
                    } else {
                        cveName = (String) reportResult.get("name");
                    }*/
                String cve = (String) reportResult.get("cve");
                Report report1 = new Report();
                report1.setTaskId(taskId);
                if (cve.isEmpty() || cve.equals("NOCVE")) {
                    report1.setCve("无CVE编号");
                } else {
                    report1.setCve(cve);
                }
                String port = reportResult.get("port").toString();
                report1.setSeverity(result.get("severity").toString());
                report1.setQod(result.get("qod").toString());
                report1.setCveName(result.get("name").toString());
                report1.setThreat(result.get("threat").toString());
                report1.setTaskName(taskName);
                reportList.add(report1);
                reportMapper.insertSelective(report1);
                //gasReport.setLevel(ipsRule1.getLevel());
                //gasReport.setLevel(result.get("threat").toString());
                //gasReport.setSeverity(result.get("severity").toString());
                //gasReport.setQod(qod);
                //gasReport.setCveName(cveName);
            }
            /*TaskReport taskReport = new TaskReport();
            taskReport.setTaskId(taskId);
            taskReport.setGasReportList(gasReportList);
            taskReportList.add(taskReport);*/
        } else {
            reportList = reportMapper.select(report);
        }
        Collections.sort(reportList, (p1, p2) -> Double.valueOf(p2.getSeverity()).compareTo(Double.valueOf(p1.getSeverity())));

        //return reportMapper.select(report);
        return reportList;
    }

    @Override
    public void createPortList(PortListVo portListVo) throws Exception {

        for (Map<String, Object> portMap : openvasTool.getPortList()) {
            if (portMap.get("name").equals(portListVo.getName())) {
                throw new ServiceException(dwEnum.FAILURE.code(), "该端口集合已存在,请确认后重新添加");
            }
        }
        openvasTool.createPortList(portListVo.getName(), portListVo.getComment(), portListVo.getPort_range());

    }

    @Override
    public void createTarget(TargetEntity target) throws Exception {
        for (TargetEntity targetExist : openvasTool.getTargetList()) {
            if (targetExist.getName().equals(target.getName())) {
                throw new ServiceException(dwEnum.FAILURE.code(), "该扫描目标已存在,请确认后重新添加");
            }
        }
        target.setReverse_lookup_only("0");
        target.setReverse_lookup_unify("0");
        target.setAlive_tests("Scan Config Default");
        openvasTool.createTarget(target);

    }

    @Override
    @Transactional
    public void createTask(TaskEntity taskEntity) throws Exception {
        //设置一个String类型 taskId 为 null
        String taskId = null;
        //这个tasksList返回15条数据
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        //把tasksList中的对象 赋值给task
        for (TaskInfoEntity task : tasksList) {
            //在用数据库里面的task和传过来的task的用户名进行比较 如果相同 则抛出异常
            if (task.getName().equals(taskEntity.getName())) {
                throw new ServiceException(dwEnum.FAILURE.code(), "该任务已存在,请确认后重新添加");
            }
        }
        //如果成功 直接创建 一个 任务
        openvasTool.createTask(taskEntity);
        //把最新更新的List集合重新赋值给tasksList
        tasksList = openvasTool.getTasksList();
        //把最新的List遍历 到task里
        for (TaskInfoEntity task : tasksList) {
            //判断找到用户传过来的对象 吧用户传过来的task的id获取出来
            if (task.getName().equals(taskEntity.getName())) {
//                吧taskId的null 替换成最新用户的Id
                taskId = task.getTaskId();
            }
        }

//        List<TargetEntity> targetList = openvasTool.getTargetList();
        /*String host = null;
        for (TargetEntity target : targetList) {
            if (target.getUuid().equals(taskEntity.getTargetId())) {
                host = target.getHosts();
            }
        }
        String reportId = openvasTool.startTask(taskId);

        TaskReportRelate trr = new TaskReportRelate();
        trr.setTaskId(taskId);
        trr.setReportId(reportId);
        trr.setHost(host);
        trr.setReportTime(new Date());
        trrMapper.insert(trr);
        if (taskEntity.getCheckType() != null && taskEntity.getCheckType().equals("ip")) {
            TaskIp taskIp = new TaskIp();
            taskIp.setTaskId(taskId);
            taskIpMapper.insert(taskIp);
        }*/
        if (taskEntity.getType() == 0) {
            startTask(taskId);
        } else if (taskEntity.getType() == 1) {
            ScanQuartz sq = new ScanQuartz();
            sq.setTaskId(taskId);
            sq.setOnOff(1);
            sq.setCron(taskEntity.getCron());
            sqMapper.insertSelective(sq);
            sqJob.run(sq);
        }

    }

    @Override
    @Transactional
    public void startTask(String taskId) {
        String reportId = null;
        String host = null;
        try {
            //执行startTask方法传入taskId  返回一个 目标 Id
            reportId = openvasTool.startTask(taskId);
            //获取最新的任务对象
            List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
            //依次遍历并赋值给任务信息实例
            for (TaskInfoEntity task : tasksList) {
                //如果数据库的任务Id = 传过来的Id的时候  找到最新的
                if (task.getTaskId().equals(taskId)) {
                    //获取下最新的目标对象 并赋值给 目标实例对象
                    List<TargetEntity> targetList = openvasTool.getTargetList();
                    //依次遍历目标实例对象
                    for (TargetEntity target : targetList) {
                        //判断目标实例对象的uuid = 任务信息实例Id的时候
                        if (target.getUuid().equals(task.getTargetId())) {
                            //就调用目标实例对象的IP 赋值给host
                            host = target.getHosts();
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

       /* TaskIp taskIp = new TaskIp();
        taskIp.setTaskId(taskId);
        TaskIp taskIp1 = taskIpMapper.selectOne(taskIp);
        taskIp.setReportId(reportId);
        if (taskIp1 != null) {
            taskIp.setId(taskIp1.getId());
            taskIpMapper.updateByPrimaryKeySelective(taskIp);
        } else {
            taskIpMapper.insertSelective(taskIp);
        }*/
        //new出来一个数据库表的对象  任务相关报告
        TaskReportRelate trr = new TaskReportRelate();
        trr.setReportTime(new Date());
        trr.setReportId(reportId);
        trr.setHost(host);
        trr.setTaskId(taskId);
        trrMapper.insert(trr);

        /*Report report = new Report();
        report.setTaskId(taskId);
        reportMapper.delete(report);*/
    }

    @Override
    @Transactional
    public void deleteTask(String taskId) {
        String groupid = "scan-Quartz";
        JobKey jobKey = new JobKey(taskId, groupid);
        JobDetail jobDetail;

        try {
            jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail != null) {
                scheduler.deleteJob(jobKey);
            }
            openvasTool.deleteTask(taskId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Report report = new Report();
        report.setTaskId(taskId);
        reportMapper.delete(report);
        TaskIp taskIp = new TaskIp();
        taskIp.setTaskId(taskId);
        taskIpMapper.delete(taskIp);
        TaskReportRelate trr = new TaskReportRelate();
        trr.setTaskId(taskId);
        /*List<TaskReportRelate> taskReportRelateList = trrMapper.select(trr);
        if (taskReportRelateList!=null && taskReportRelateList.size()>0){
            assetsMapper.updateScore(taskReportRelateList.get(0).getHost());
        }*/
        trrMapper.delete(trr);
        ScanQuartz sq = new ScanQuartz();
        sq.setTaskId(taskId);
        sqMapper.delete(sq);


    }

    @Override
    public List<Report> getReportByReportId(String reportId) {
        List<Report> reportList = new ArrayList<>();
        Report report = new Report();
        report.setReportId(reportId);
        List<Report> reports = reportMapper.select(report);
        if (reports != null && reports.size() > 0) {
            reportList = reports;
        } else {
            try {
                Map<String, Object> resultMap = openvasTool.getReport(reportId);
                List<Map<String, Object>> results = (List<Map<String, Object>>) resultMap.get("results");
                TaskReportRelate trr = new TaskReportRelate();
                trr.setReportId(reportId);
                String host = trrMapper.selectOne(trr).getHost();
                for (Map<String, Object> result : results) {
                    if (result.get("hostname").equals(host) || result.get("host").equals(host)) {
                        String resultId = (String) result.get("resultId");
                        //resultIdList.add(resultId);
                        Map<String, Object> reportResult = openvasTool.getReportResult(resultId);
                        String cve = (String) reportResult.get("cve");
                        TaskReportRelate tsr = new TaskReportRelate();
                        tsr.setReportId(reportId);
                        TaskReportRelate tsr1 = trrMapper.selectOne(tsr);
                        Report report1 = new Report();
                        report1.setTaskId(tsr1.getTaskId());
                        if (cve == null || cve.isEmpty() || cve.equals("NOCVE")) {
                            report1.setCve("无CVE编号");
                        } else {
                            report1.setCve(cve);
                        }
                        report1.setIp(reportResult.get("host").toString());
                        report1.setHostName(reportResult.get("hostname").toString());
                        report1.setPort(reportResult.get("port").toString());
                        report1.setSeverity(result.get("severity").toString());
                        report1.setQod(result.get("qod").toString());
                        String cveName = null;
                        String solution = null;
                        Translate translate = translateMapper.selectByPrimaryKey(result.get("name").toString());
                        if (translate != null) {
                            cveName = translate.getName();
                            solution = translate.getSolution();
                        } else {
                            cveName = result.get("name").toString();
                            solution = reportResult.get("solution").toString();
                        }
                        report1.setCveName(cveName);
                        report1.setThreat(result.get("threat").toString());
                        report1.setReportId(reportId);
                        report1.setSummary(reportResult.get("summary").toString());
                        report1.setImpact(reportResult.get("impact").toString());

//                       虚拟字段
//                        report1.setInfluence("无");
//                        report1.setAuthenticationinfo("成功");
//                        report1.setExistExp("有");
//                        report1.setInfluence(reportResult.get(""));
                /*if (reportResult.get("solution")!=null) {
                    report1.setSolution(reportResult.get("solution").toString());
                }*/
                        report1.setSolution(solution);
                        if (!reportList.contains(report1)) {
                            reportList.add(report1);
                            reportMapper.insertSelective(report1);
                        }
                        //reportMapper.insertSelective(report1);
                        //gasReport.setLevel(ipsRule1.getLevel());
                        //gasReport.setLevel(result.get("threat").toString());
                        //gasReport.setSeverity(result.get("severity").toString());
                        //gasReport.setQod(qod);
                        //gasReport.setCveName(cveName);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Collections.sort(reportList, (p1, p2) -> Double.valueOf(p2.getSeverity()).compareTo(Double.valueOf(p1.getSeverity())));
        return reportList;

    }

    @Override
    public List<Report> getReportByHost(String host) {
        List<TaskInfoEntity> taskList = new ArrayList<>();
        List<Report> reportList = new ArrayList<>();
        try {
            taskList = openvasTool.getTasksList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        TaskReportRelate trr = new TaskReportRelate();
        trr.setHost(host);
        List<TaskReportRelate> trrList = trrMapper.select(trr);
        if (trrList != null) {
            Collections.sort(trrList, (p1, p2) -> p2.getReportTime().compareTo(p1.getReportTime()));
            //for (TaskInfoEntity task : taskList) {
                //if (task.getName().contains(host) && task.getName().contains(trrList.get(0).getReportTime().toString().substring(0, 16))) {
                            /*ScanQuartz sq = sqMapper.selectByPrimaryKey(task.getTaskId());
                            if (sq != null) {*/
                    //if (task.getStatus().equals("已完成")) {
                        //reportList = getReportByReportId(trrList.get(0).getReportId());
                        Report report = new Report();
                        report.setReportId(trrList.get(0).getReportId());
                        reportList = reportMapper.select(report);
                    //} else {
                        if (reportList.size()==0 && trrList.size() > 1) {
                            //reportList = getReportByReportId(trrList.get(1).getReportId());
                            //Report report = new Report();
                            report.setReportId(trrList.get(1).getReportId());
                            reportList = reportMapper.select(report);
                        }
                    }
                    //break;
                    //}
                //}
           // }
            Collections.sort(reportList, (p1, p2) -> Double.valueOf(p2.getSeverity()).compareTo(Double.valueOf(p1.getSeverity())));
        //}
        return reportList;
    }

    @Override
    public void deleteAllByIp(String ip) {
        String targetId = null;
        String taskId = null;
        try {
            for (TargetEntity targetExist : openvasTool.getTargetList()) {
                if (targetExist.getHosts().equals(ip)) {
                    targetId = targetExist.getUuid();
                }
            }

            List<TaskInfoEntity> taskList = openvasTool.getTasksList();
            for (TaskInfoEntity task : taskList) {
                if (task.getTargetId().equals(targetId)) {
                    taskId = task.getTaskId();
                }
            }
            deleteTask(taskId);
            openvasTool.deleteTarget(targetId);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void addTargetAndTasksRabbitmq(CheckEntity checkEntity) {
        Date date = new Date();
        //网站备案使用
        //List<Integer> recordIdList = rgMapper.getRecord(checkEntity.getGroupId());
        //List<String> hostList = rnMapper.getHosts(recordIdList);

        //镁拓项目使用
        List<String> hostList = new ArrayList<>();
        if (checkEntity.getGroupId() != 0) {
            List<Integer> assetIdList = assetandgroupMapper.getAsset(checkEntity.getGroupId());
            hostList = assetsMapper.getHosts(assetIdList);
        } else {
            String[] hosts = checkEntity.getHosts();
            for (String host : hosts) {
                hostList.add(host);
            }
        }
        GroupTask groupTask = new GroupTask();
        groupTask.setTaskName(date + "___" + checkEntity.getName());
        groupTask.setCheckType(Integer.valueOf(checkEntity.getType()));
        groupTask.setGroupId(checkEntity.getGroupId());
        groupTask.setTime(date);
        groupTask.setCron(checkEntity.getCron());
        groupTaskMapper.insert(groupTask);
        for (String host : hostList) {
            CheckEntity check = new CheckEntity();
            check.setName(date + "___" + checkEntity.getName() + "___" + host);
            check.setType(checkEntity.getType());
            check.setCron(checkEntity.getCron());
            check.setHosts(new String[]{host});
            try {
                rabbitMQServiceImpl.sendMsg(JSON.toJSONString(check));
            } catch (Exception e) {
                e.printStackTrace();
            }
            MqTask mqTask = new MqTask();
            mqTask.setCron(checkEntity.getCron());
            mqTask.setDate(date);
            mqTask.setTaskName(date + "___" + host + "___" + host);
            mqTask.setType(checkEntity.getType());
            mqTask.setHost(host);
            mqTask.setGroupTaskId(groupTask.getId());
            mqTaskMapper.insert(mqTask);
        }
    }

    @Override
    public List<IpResultEntity> getScore() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        List<String> ip = taskService.getScore();
        // List<Report> reports = new ArrayList<>();
        List<IpResultEntity> ipResult = new ArrayList<>();
        //获取所有任务
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        Map<String, TaskInfoEntity> taskListNewTime = new HashMap<>();
        for (TaskInfoEntity taskInfoEntity : tasksList) {
            String reportId = taskInfoEntity.getReportId();
            Report reportselect = new Report();
            reportselect.setReportId(reportId);
            //调用方法获取Report(报告) 内容
            if (taskInfoEntity.getStatus().equals("已完成")) {
                List<Report> reports = reportMapper.select(reportselect);
                if (reports != null && reports.size() > 0) {
                    // reports = taskService.getReportByReportId(taskInfoEntity.getReportId());
                    //判断漏洞并设置评分
                    int hig = 0;
                    int mid = 0;
                    int low = 0;
                    int warning = 0;
                    for (Report report : reports) {
                        String threat = report.getThreat();
                        if (threat.equals("低")) {
                            low++;
                        } else if (threat.equals("中")) {
                            mid++;
                        } else if (threat.equals("高")) {
                            hig++;
                        } else if (threat.equals("Log")) {
                            warning++;
                        }
                    }
                    //算评分
                    String score = ScoreUtil.calculationScore(hig, mid, low, warning);
                    //设置评分
                    taskInfoEntity.setSeverity(score);
                    String s1 = splitUrl(taskInfoEntity);
                    taskInfoEntity.setHost(s1);

                    TaskInfoEntity lastInfo = taskListNewTime.get(s1);
                    if (lastInfo == null) {
                        taskListNewTime.put(s1, taskInfoEntity);
                    } else {
                        // 比较时间
                        long lastTime1 = simpleDateFormat.parse(lastInfo.getCheckTime()).getTime();
                        long time = simpleDateFormat.parse(taskInfoEntity.getCheckTime()).getTime();
                        if (time > lastTime1) {
                            taskListNewTime.put(s1, taskInfoEntity);
                        }
                    }
                }

            }
        }
        //遍历map获取report
        Set<Map.Entry<String, TaskInfoEntity>> entries = taskListNewTime.entrySet();
        for (Map.Entry<String, TaskInfoEntity> entry : entries) {
            if (ipResult.size() < 10) {
                ipResult.add(new IpResultEntity(entry.getKey(), Double.valueOf(entry.getValue().getSeverity())));
            }
        }

        ipResult.sort(new Comparator<IpResultEntity>() {
            @Override
            public int compare(IpResultEntity o1, IpResultEntity o2) {
                return Double.compare(o1.getSum(), o2.getSum());
            }
        });
        return ipResult;
    }

    @Override
    public List<IpResultEntity> getHig() throws Exception {
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        List<IpResultEntity> ipResult = new ArrayList<>();
        getCveSum(tasksList, ipResult, "高");
        return ipResult;
    }

    @Override
    public List<IpResultEntity> getMid() throws Exception {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
//        List<IpResultEntity> ipResultEntities = new ArrayList<>();
//        Map<String, TaskInfoEntity> lastTime = new HashMap<>();
        List<IpResultEntity> ipResult = new ArrayList<>();
        getCveSum(tasksList, ipResult, "中");
//        List<IpResultEntity> ipResultEntities2 = new ArrayList<>();
//        for (TaskInfoEntity taskInfoEntity : tasksList) {
//            List<Report> reports = taskService.getReportByReportId(taskInfoEntity.getReportId());
//            double Mid = 0;
//            for (Report report : reports) {
//                String threat = report.getThreat();
//                if (threat.equals("中")) {
//                    Mid++;
//                }
//            }
//            String s1 = splitUrl(taskInfoEntity);
//            taskInfoEntity.setRisk(Mid);
//            TaskInfoEntity taskInfoEntity1 = lastTime.get(s1);
//            if (taskInfoEntity1 == null) {
//                lastTime.put(s1, taskInfoEntity);
//            } else {
//
//                long time = simpleDateFormat.parse(taskInfoEntity1.getCheckTime()).getTime();
//                long time1 = simpleDateFormat.parse(taskInfoEntity.getCheckTime()).getTime();
//                if (time1 > time) {
//                    lastTime.put(s1, taskInfoEntity);
//                }
//            }
//
//
//        }
//        Set<Map.Entry<String, TaskInfoEntity>> entries = lastTime.entrySet();
//        for (Map.Entry<String, TaskInfoEntity> entry : entries) {
//            if(ipResult.size()<10) {
//                ipResult.add(new IpResultEntity(entry.getKey(), entry.getValue().getRisk()));
//            }
//        }
//        ipResult.sort(new Comparator<IpResultEntity>() {
//            @Override
//            public int compare(IpResultEntity o1, IpResultEntity o2) {
//                return Double.compare(o2.getSum(), o1.getSum());
//            }
//        });
        return ipResult;
    }

    @Override
    public List<IpResultEntity> getLow() throws Exception {
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        List<IpResultEntity> ipResult = new ArrayList<>();
        getCveSum(tasksList, ipResult, "低");
        return ipResult;
    }


    @Override
    public List<IpResultEntity> getWarning() throws Exception {
        List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
        List<IpResultEntity> ipResult = new ArrayList<>();
        getCveSum(tasksList, ipResult, "Log");
        return ipResult;
    }

    @Override
    public List<ResultInfoPage> getResultPageByDateAndLvAndIpAndAssetsName(String date1, String date2, String assetsName, String lv, String ip, Integer pageNum, Integer pageSize) {
        List<ResultInfoPage> list = new ArrayList();
        try {
            //虚拟数据
            ArrayList<Report> objects = new ArrayList<>();
            //获取所有任务列表
            List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
            //遍历任务列表
            for (TaskInfoEntity taskInfoEntity : tasksList) {
                //通过任务列表的 的报告id 获取一个 报告对象
                List<Report> reportByReportId = taskService.getReportByReportId(taskInfoEntity.getReportId());
                for (Report report : reportByReportId) {
                    objects.add(report);
                }
                //通过任务的名字 分隔出来 ip (任务的名字自带ip,截取方式是截取最后_的东西(ip),截取不到或者截取异常没有按照代码生成扫描进程,如要修改splitUrl即可)
                String sulitIp = splitUrl(taskInfoEntity);
                Assets asset = assetsMapper.getAsset(sulitIp);
//                System.out.println("name"+asset.getAssetsname());
//                System.out.println("dengji"+asset.getLevel());
//                System.out.println("ip"+asset.getIp());
                //由于拿到的结果只是一个集合做判断的时候只能操作集合来进行判断
                //如果项目后期增加elasticsearch的时候可以用es来操作数据 来使得维护变得轻松
                pageService.PageResult(list, taskInfoEntity, asset, objects, date1, date2, assetsName, lv, ip);
//                new PageService().PageResult(list,taskInfoEntity,asset,reportByReportId,date1,date2,assetsName,lv,ip);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("后台内部错误,请重试");
        }
        return list;
    }

    public void getCveSum(List<TaskInfoEntity> tasksList, List<IpResultEntity> ipResult, String Threat) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Map<String, TaskInfoEntity> lastTime = new HashMap<>();

        for (TaskInfoEntity taskInfoEntity : tasksList) {
            String reportId = taskInfoEntity.getReportId();
            Report reportselect = new Report();
            reportselect.setReportId(reportId);
            //调用方法获取Report(报告) 内容
            if (taskInfoEntity.getStatus().equals("已完成")) {
                List<Report> reports = reportMapper.select(reportselect);
                if (reports != null && reports.size() > 0) {
                    //if (taskInfoEntity.getStatus().equals("已完成")) {
                    //List<Report> reports = taskService.getReportByReportId(taskInfoEntity.getReportId());
                    double threatSum = 0;
                    for (Report report : reports) {
                        String threat = report.getThreat();
                        if (threat.equals(Threat)) {
                            threatSum++;
                        }
                    }
                    String s1 = splitUrl(taskInfoEntity);
                    taskInfoEntity.setRisk(threatSum);
                    TaskInfoEntity taskInfoEntity1 = lastTime.get(s1);
                    if (taskInfoEntity1 == null) {
                        lastTime.put(s1, taskInfoEntity);
                    } else {
                        long time = simpleDateFormat.parse(taskInfoEntity1.getCheckTime()).getTime();
                        long time1 = simpleDateFormat.parse(taskInfoEntity.getCheckTime()).getTime();
                        if (time1 > time) {
                            lastTime.put(s1, taskInfoEntity);
                        }
                    }
                }
            }


        }
        Set<Map.Entry<String, TaskInfoEntity>> entries = lastTime.entrySet();
        for (Map.Entry<String, TaskInfoEntity> entry : entries) {
            if (ipResult.size() < 10) {
                ipResult.add(new IpResultEntity(entry.getKey(), entry.getValue().getRisk()));
            }
        }
        ipResult.sort(new Comparator<IpResultEntity>() {
            @Override
            public int compare(IpResultEntity o1, IpResultEntity o2) {
                return Double.compare(o2.getSum(), o1.getSum());
            }
        });
    }

    public String splitUrl(TaskInfoEntity taskInfoEntity) {
        String taskInfoEntityUri = taskInfoEntity.getName().split("_")[taskInfoEntity.getName().split("_").length - 1];
        String uri = taskInfoEntityUri.split("\\[")[0];
        return uri;
    }
}
